package org.cst.activity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ClientActivity extends Activity {

	public static Handler mHandler=new Handler();
	TextView textView,textView2;
	EditText editText2;
	String tmp;
	Socket clientSocket;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.client);
		
		textView=(TextView) findViewById(R.id.TextView01);
		textView2=(TextView) findViewById(R.id.textView2);
		editText2=(EditText) findViewById(R.id.EditText02);
		
		Thread t=new Thread(readData);
		
		t.start();
		
		Bundle bu=this.getIntent().getExtras();
		textView2.setText(bu.getString("name"));
		Button button1=(Button) findViewById(R.id.Button01);
		
		button1.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				try {
					if(clientSocket.isConnected())
					{
						BufferedWriter bw;
						try{
							bw=new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
							
							bw.write(textView2.getText()+":"+editText2.getText()+"\n");
							
							bw.flush();
						}catch(IOException e){
							Toast.makeText(ClientActivity.this, "瀹㈡埛绔緭鍏ヨ緭鍑洪敊璇瘇", Toast.LENGTH_LONG).show();
						}
						editText2.setText("");
					}
				} catch (NullPointerException e) {
				//		Toast.makeText(ClientActivity.this, "杩炴帴鏈嶅姟鍣ㄧ澶辫触锛岃纭鏈嶅姟鍣ㄥ凡寮�惎锛�", Toast.LENGTH_LONG).show();
					}
				}
		});
	}
	
	private Runnable updateText=new Runnable(){
		public void run(){
			textView.append(tmp+"\n");
		}
	};
	
	private Runnable readData=new Runnable(){
		public void run(){
			try{
				int serverPort=6001;
				clientSocket=new Socket("192.168.0.3",serverPort);
				
				BufferedReader br=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
				
				while(clientSocket.isConnected()){
					tmp=br.readLine();
					if(null!=tmp)
					{
						mHandler.post(updateText);
					}
				}
			}catch(IOException e){
				Toast.makeText(ClientActivity.this, "瀹㈡埛绔緭鍏ヨ緭鍑洪敊璇瘇", Toast.LENGTH_LONG).show();
			}
		}
	};
}
